#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member

using System;
using System.Threading;
using UnityEngine;

namespace EntityKit.Runtime
{
    /// <summary>
    /// 用于等待帧结束的辅助组件
    /// </summary>
    internal class FrameWaiter : MonoBehaviour
    {
        private System.Action _callback;
        private CancellationToken _cancellationToken;
        
        public void WaitForEndOfFrame(System.Action callback, CancellationToken cancellationToken)
        {
            _callback = callback;
            _cancellationToken = cancellationToken;
            StartCoroutine(Wait());
        }
        
        private System.Collections.IEnumerator Wait()
        {
            yield return new WaitForEndOfFrame();
            
            if (!_cancellationToken.IsCancellationRequested)
            {
                _callback?.Invoke();
            }
            
            Destroy(this);
        }
    }
}